package com.heima.search.listener;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author XHui
 * @Since 2024/3/16 17:02
 * @Version 1.0
 */
@Slf4j
@Component
public class ArticleDocAddOrDeleteListener {

    @Resource
    private ArticleFeign articleFeign;

    @Resource
    private ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare =
    @Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE)
    )
    public void handleNewsUpMsg(String articleId) {
        log.info("监听到上架文章id：{}", articleId);

        // 1. 根据articleId查询文章信息 -> 调取article微服务
        ResponseResult<SearchArticleVO> responseResult = articleFeign.findArticle(Long.valueOf(articleId));
        SearchArticleVO  searchArticleVO = responseResult.getData();
        if(!responseResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "文章不存在，文章id：" + articleId);
            log.error("文章不存在，文章id：{}，无须将mysql中的数据备份到es中", articleId);
        }
        // 2. 调用es的api，将文章信息写入es
        articleSearchService.saveArticleDoc(searchArticleVO);

    }

    @RabbitListener(queuesToDeclare =
    @Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handleNewsDownMsg(String articleId) {
        log.info("监听到下架文章id：{}", articleId);

        // 2. 调用articleId 的api，将文章信息从es中删除
        articleSearchService.deleteArticleDoc(articleId);
    }
}
